<?php
class LoginService
{
	/**
	 * 登陆检测
	 * @Author   Leikes
	 * @DateTime 2016-01-25T16:32:43+0800
	 * @param    string                   $email    邮箱号
	 * @param    string                   $password 密码
	 * @return   excetion                             异常信息
	 */
	public function loginCheck($email,$password)
	{
		$data=[
			'email'=>$email,
			'password'=>$password
		];
		try
		{
			$this->verifyLoginInfo($data);

			if (!Auth::attempt(array('email' => $email, 'password' => $password)))
			{
			    throw new PasswordErrorException;
			}
			$userId=Auth::id();
			$userRole=User_role::where('user_id','=',$userId)->where('role_id','=',Config::get('systemConfig.system.role_id.system_admin'))->first();
			if(empty($userRole))
			{
				throw new NormalException;
			}
			throw new AdminLoginException;
		}
		catch(FieldValueAuthException $e)
		{
			return $e;
		}
		catch(UsernameErrorException $e)
		{
			return $e;
		}
		catch(PasswordErrorException $e)
		{
			return $e;
		}
		catch(NormalException $e)
		{
			return $e;
		}
		catch(AdminLoginException $e)
		{
			return $e;
		}

	}

	/**
	 * 登陆信息校验
	 * @Author   Leikes
	 * @DateTime 2016-01-25T16:33:57+0800
	 * @param    array                   $date 用户名和密码的数组
	 * @throws   exception                         抛出异常信息
	 */
	private function verifyLoginInfo($data)
	{
		$rules=[
			'email'=>'required|email',
			'password'=>'required'
		];
		// $messages=[
		// 	'required'=>':attribute为空,请确认后重新输入',
		// 	'email'=>':attribute必须为邮箱账号,请确认后重新输入'
		// ];
		// $customAttributes=[
		// 	'email'=>'用户名',
		// 	'password'=>'密码'
		// ];
		$validation = Validator::make($data,$rules);
		if( $validation->fails() )
		{
			throw new FieldValueAuthException( $validation->messages()->first() );
		}

		$rules=[
			'email'=>'exists:users,email',
		];
		$validation = Validator::make($data,$rules);
		if( $validation->fails() )
		{
			throw new UsernameErrorException;
		}

	}
}
?>